package com.magicalcoder.pigeon.common.message;

import com.magicalcoder.pigeon.common.protobuf.ProtostuffUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * Created by hzhedongyu on 2017/5/24.
 */
public class PigeonDecoder extends ByteToMessageDecoder{

    private Class<?> clazz;
    public PigeonDecoder(Class<?> clazz){
        this.clazz = clazz;
    }
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if(byteBuf.readableBytes()<4){
            return;
        }
        byteBuf.markReaderIndex();
        int length = byteBuf.readInt();

        if(byteBuf.readableBytes()<length){
            byteBuf.resetReaderIndex();
            return;
        }
        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes);
        Object object = ProtostuffUtil.deserialize(bytes,clazz);
        list.add(object);
    }
}
